package ui.task;

import cerebrum.cache.RunTimeContextCache;
import cerebrum.cache.UsageTimeCache;
import cerebrum.common.ConfigPropertiesUtil;
import cerebrum.common.KeyboardHook;
import cerebrum.common.MouseHook;
import cerebrum.cache.ImagesDataLoaderCache;
import javafx.application.Platform;
import ui.panel.showroom.ScreenSaverStage;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Timer;
import java.util.TimerTask;

public class ScreenProtectioTask extends Thread {


    public ScreenProtectioTask() {

    }

    public void run() {
        //屏保唤醒时间
        int screenSaver = Integer.valueOf(ConfigPropertiesUtil.get("screenSaver"));
        if (screenSaver != 0) {
            //启动鼠标监控钩子
            MouseHook mhook = new MouseHook();
            new Thread(mhook).start();
            //启动屏保监视
            dispatcher(Long.valueOf(screenSaver));
            //启动键盘监控钩子
            KeyboardHook keyboardHook = new KeyboardHook();
            new Thread(keyboardHook).start();
        }
    }

    /**
     * @param frequency 屏保唤醒时间
     */
    private void dispatcher(Long frequency) {
        //定时器
        final Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                dateCheck(frequency);
                if (!RunTimeContextCache.getThreadStatus()) {
                    timer.cancel();// 停止定时器
                }
            }
        };
        // 立即执行一次，后面每隔1秒执行一次
        timer.schedule(task, 0, 1000);
    }

    /**
     * 依靠上方的定时任务判断：
     * 1.判断键盘及鼠标钩子是否在往队列中添加操作数据，如果未操作时间大于屏保唤醒时间则唤醒屏保，
     * 2.屏保唤醒状态下，如一直未往队列中添加操作数据则一直保持屏保唤醒状态，如果添加了数据，则收起屏保界面
     *
     * @param secondNum
     */
    private void dateCheck(Long secondNum) {
        try {
            System.out.println("...................................");
            LocalDateTime dateTimes = UsageTimeCache.getDateTimes();//获取队列中的最新数据
            LocalDateTime lastDate = UsageTimeCache.getLastDate();//上一次操作时间
            boolean showStatus;
//            try {
//                ScreenSaverStage screenSaverStage = ScreenSaverStage.getInstance();
//                showStatus = screenSaverStage.isShowing();//屏保状态
//            } catch (NullPointerException e) {
            showStatus = ImagesDataLoaderCache.getScreenTaskStatus();
//            }
            //如果队列中没有数据了，那就说明电脑停止使用，相反，则队列中会持续有数据
            if (dateTimes != null) {
                if (showStatus == false) {
                    //记录下最新的操作时间
                    UsageTimeCache.setLastDate(dateTimes);
                } else {
                    //屏保展开,则说明上一次判断未在使用电脑，开始重新使用电脑则把屏保隐藏调
                    UsageTimeCache.setLastDate(dateTimes);
                    updateScreenSaver(false);
                }
            } else {
                if (showStatus == false) {
                    long seconds = Duration.between(lastDate, LocalDateTime.now()).getSeconds();
                    System.out.println("seconds:" + seconds);
                    if (Math.abs(seconds) >= secondNum) {
                        updateScreenSaver(true);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新ui
     */
    private void updateScreenSaver(Boolean b) {
        Platform.runLater(()->{
                if (b) {
                    ImagesDataLoaderCache.setScreenTaskStatus(true);
                    ScreenSaverStage screenSaver = ScreenSaverStage.getInstance();
                    screenSaver.verseStyle();
                    screenSaver.randomStyle();
                    screenSaver.screenSaverStyleSetting();
                    //启动时钟走时
                    screenSaver.startTimer();
                    screenSaver.show();
                    RunTimeContextCache.setTimerStatus(true);
                } else {
                    ImagesDataLoaderCache.setScreenTaskStatus(false);
                    ScreenSaverStage screenSaver = ScreenSaverStage.getInstance();
                    screenSaver.verseClean();
                    screenSaver.close();
                    RunTimeContextCache.setTimerStatus(false);
                }

        });
    }
}
